﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.IO;
using System.Net;
using Caliburn.Micro;
using OI.Framework;

namespace OI.Async
{
    public class DataDownload : IResult
    {
        public Uri ResourceUri { get; private set; }
        public Stream Results { get; private set; }

        public DataDownload(Uri resourceUri)
        {
            ResourceUri = resourceUri;
        }

        public event EventHandler<ResultCompletionEventArgs> Completed;


        public void Execute(ActionExecutionContext context)
        {
            var web = new WebClient();
            web.OpenReadCompleted += WebOpenReadCompleted;
            web.OpenReadAsync(ResourceUri);
        }


        void WebOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                IoC.Get<IShell>().HandleException(e.Error, "Error downloading package");
            }
            else if (!e.Cancelled)
            {
                Results = e.Result;
            }

            Completed(this, new ResultCompletionEventArgs { Error = e.Error });
        }
    }
}
